package io.shuttle.mbe_app.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import io.shuttle.mbe_app.MainActivity
import io.shuttle.mobilebrowserextension.R
import kotlin.also
import kotlin.jvm.java

class ForgroundService : Service() {
    companion object {
        private const val NOTIFICATION_ID = 111
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val notification = createNotification()
        startForeground(NOTIFICATION_ID, notification)
        val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        nm.notify(NOTIFICATION_ID, notification)
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }


    private fun createNotification(): Notification {
        createNotificationChannel()
        val builder = NotificationCompat.Builder(this, "trtc")
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setWhen(System.currentTimeMillis())
            .setContentTitle("TRTC")
            .setContentText("TRTC in WebView")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        val intent = Intent(this, MainActivity::class.java).also {
            it.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        builder
            .setContentIntent(pendingIntent)
            .setOngoing(true);
        return builder.build();
    }

    fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "TRTC"
            val description = "TRTC in WebView"
            val importance = NotificationManager.IMPORTANCE_HIGH
            val channel = NotificationChannel("trtc", name, importance)
            channel.description = description
            val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            nm.createNotificationChannel(channel)
        }
    }
}